package com.attendance.service;

import com.alibaba.fastjson.JSONObject;
import com.attendance.annotation.Supplement;
import com.attendance.annotation.type.OperationType;
import com.attendance.java.StringUtils;
import com.attendance.mapper.TaskUserLogMapper;
import com.attendance.pojo.TaskUserLog;
import com.attendance.pojo.UserDetails;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 任务记录服务impl
 *
 * @author 今朝
 * @date 2021/03/24
 */
@Service
public class TaskRecordServiceImpl {
    @Autowired
    TaskUserLogMapper taskUserLogMapper;
    @Autowired
    UserDetailsServiceImpl userDetailsService;
    @Autowired
    TaskServiceImpl taskService;

    public Page<TaskUserLog> getListPage(Integer pageNum, Integer limit) {
        Page<TaskUserLog> page = new Page<>(pageNum, limit);
        QueryWrapper<TaskUserLog> queryWrapper = new QueryWrapper<>();
        taskUserLogMapper.selectPage(page, queryWrapper);
        for (TaskUserLog log : page.getRecords()) {
            log.setUserName(userDetailsService.selectById(log.getUserId()).getName());
            log.setTaskName(taskService.selectById(log.getTaskId()).getName());
        }
        return page;
    }

    public Page<TaskUserLog> getListPage(Integer pageNum, Integer limit,String searchParams) {
        JSONObject parse = JSONObject.parseObject(searchParams);
        QueryWrapper<TaskUserLog> queryWrapper = new QueryWrapper<>();
        for (String key : parse.keySet()) {
            if (!"".equals(parse.get(key).toString().trim())){
                queryWrapper.eq(key, parse.get(key));
            }
        }
        Page<TaskUserLog> page = new Page<>(pageNum, limit);
        taskUserLogMapper.selectPage(page, queryWrapper);
        for (TaskUserLog log : page.getRecords()) {
            log.setUserName(userDetailsService.selectById(log.getUserId()).getName());
            log.setTaskName(taskService.selectById(log.getTaskId()).getName());
        }
        return page;
    }

    @Supplement(type = OperationType.PUT)
    public Boolean add(TaskUserLog log,String taskIds) throws Exception {
        List<Long> tIds = StringUtils.strToIdsByComma(taskIds);
        Date date = new Date();
        log.setLogDate(date);
        log.setLogTime(date);
        for (Long tid : tIds) {
            log.setTaskId(tid);
            try{
                taskUserLogMapper.insert(log);
            }catch (Exception e){
                throw new Exception("请不要重复签到");
            }
        }
        return true;
    }
}
